''' 
playwright装饰器
用它装饰的例子请看example_pwDeco.py中的get_html函数
pw_deco装饰器
装饰器参数：
    pPort:传入你本地打开的代理软件的port
    headless:控制无头模式的，默认是False，关闭无头模式
    Brow:选择playwright使用的浏览器种类，参数有"webkit","firefox"和"chromium"
    anony:浏览器的匿名访问开关，默认为True,默认匿名访问



好像创建一个类会更好？
流畅的python还没看到对象，看完对象再写一个。
不行，装饰器只能给一个函数用，同时装饰俩函数会出问题
'''
from functools import wraps
import random

from playwright.sync_api import sync_playwright 

devicesName = (
    'Desktop Chrome HiDPI',
    'Desktop Edge HiDPI',
    'Desktop Firefox HiDPI',
    'Desktop Safari',
    'Desktop Chrome',
    'Desktop Edge',
    'Desktop Firefox'
    )

def pw_deco(pPort=10809,headless=False,Brow="webkit",anony=True):
    '''
    装饰器工厂函数
    返回装饰器

    playwright装饰器
    用它装饰的例子请看example_pwDeco.py中的get_html函数
    参数：
        pPort:传入你本地打开的代理软件的port
        headless:控制无头模式的，默认是False，关闭无头模式
        Brow:选择playwright使用的浏览器种类，参数有"webkit","firefox"和"chromium"
        anony:浏览器的匿名访问开关，默认为True,默认匿名访问

    '''
    def decorate(func):
        """
         装饰器函数
         返回被装饰后的函数
        """
        nonlocal pPort,headless,Brow,anony
        pw = sync_playwright().start()
        ipPort = f'127.0.0.1:{pPort}'
        proxy = "http://" + ipPort
        if not anony:
            if Brow == "firefox":
                Brow = "chromium"
            BROWSER = eval('pw.'+Brow)
            #BROWSER = eval('pw.chromium')
            browser = BROWSER.launch_persistent_context(
                user_data_dir=r'D:\杨博\pw_Temp',
                headless=headless,
                proxy={"server":proxy},
                #channel="msedge",
                #chromium_sandbox=True
            )
        else:
            BROWSER = eval('pw.'+Brow)
            browser = BROWSER.launch(
                headless=headless,
                proxy={"server":proxy}
            )
        @wraps(func)
        def func_decoed(*args,off=False):
            """ 被装饰后的函数"""
            if not off:
                if not anony:
                    device = {}
                else:
                    device = pw.devices[random.choice(devicesName)]
                result = func(*args,browser=browser,device=device)
                return result
            else:
                pw.stop()
        
        return func_decoed
    return decorate

'''def pw_deco(func):
    pw = sync_playwright().start()
    ipPort = '127.0.0.1:10809'
    proxy = "http://" + ipPort
    chrome = pw.chromium
    browser = chrome.launch(
        headless=False,
        proxy={"server":proxy}
    )
    @wraps(func)
    def func_decoed(*args,off=False):
        if not off:
            device = pw.devices[random.choice(devicesName)]
            result = func(*args,browser=browser,device=device)
            return result
        else:
            pw.stop()
    
    return func_decoed'''

